<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>我的收藏</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="refreshFavorites">
          刷新
        </el-button>
      </div>

      <!-- 收藏列表 -->
      <div v-if="favoritesList.length > 0">
        <el-row :gutter="20">
          <el-col
            v-for="favorite in favoritesList"
            :key="favorite.favoriteId"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            class="favorite-item"
          >
            <el-card shadow="hover" class="favorite-card">
              <div class="card-header">
                <span class="question-title">{{ favorite.question.title }}</span>
                <div>
                  <el-tag
                    :type="getDifficultyType(favorite.question.difficultyLevel)"
                    size="small"
                    style="margin-right: 5px"
                  >
                    {{ getDifficultyText(favorite.question.difficultyLevel) }}
                  </el-tag>
                  <el-tag type="info" size="small">
                    {{ getQuestionTypeText(favorite.question.questionType) }}
                  </el-tag>
                </div>
              </div>

              <div class="question-content">
                <p>{{ truncateText(favorite.question.content, 100) }}</p>
              </div>

              <div class="card-footer">
                <el-button-group>
                  <el-button size="small" type="primary" @click="practiceQuestion(favorite.question)">
                    开始练习
                  </el-button>
                  <el-button size="small" type="danger" @click="removeFavorite(favorite)" :loading="favorite.removing">
                    取消收藏
                  </el-button>
                </el-button-group>
              </div>

              <div class="collect-time">
                收藏时间：{{ formatDate(favorite.createTime) }}
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 分页 -->
        <el-pagination
          v-if="total > pageSize"
          :current-page="currentPage"
          :page-sizes="[8, 16, 24, 32]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="margin-top: 20px; text-align: center;"
        />
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <el-empty description="您还没有收藏任何题目">
          <el-button type="primary" @click="goToPractice">去练习题目</el-button>
        </el-empty>
      </div>
    </el-card>

    <!-- 题目练习对话框 -->
    <el-dialog title="题目练习" :visible.sync="practiceDialogVisible" width="70%">
      <div v-if="selectedQuestion">
        <div class="practice-question">
          <h3>{{ selectedQuestion.title }}</h3>
          <div class="question-content">
            <p>{{ selectedQuestion.content }}</p>
          </div>

          <div class="answer-section">
            <!-- 单选题 -->
            <div v-if="selectedQuestion.questionType === 'single'" class="options-container">
              <el-radio-group v-model="practiceAnswer">
                <el-radio
                  v-for="option in selectedQuestion.options"
                  :key="option.optionId"
                  :label="option.optionKey"
                  class="option-item"
                >
                  {{ option.optionKey }}. {{ option.optionContent }}
                </el-radio>
              </el-radio-group>
            </div>

            <!-- 多选题 -->
            <div v-else-if="selectedQuestion.questionType === 'multiple'" class="options-container">
              <el-checkbox-group v-model="practiceAnswerArray">
                <el-checkbox
                  v-for="option in selectedQuestion.options"
                  :key="option.optionId"
                  :label="option.optionKey"
                  class="option-item"
                >
                  {{ option.optionKey }}. {{ option.optionContent }}
                </el-checkbox>
              </el-checkbox-group>
            </div>

            <!-- 判断题 -->
            <div v-else-if="selectedQuestion.questionType === 'judge'" class="options-container">
              <el-radio-group v-model="practiceAnswer">
                <el-radio label="true" class="option-item">正确</el-radio>
                <el-radio label="false" class="option-item">错误</el-radio>
              </el-radio-group>
            </div>

            <!-- 简答题 -->
            <div v-else-if="selectedQuestion.questionType === 'essay'" class="options-container">
              <el-input
                v-model="practiceAnswer"
                type="textarea"
                :rows="6"
                placeholder="请输入您的答案..."
              />
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="practiceDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPracticeAnswer" :disabled="!hasPracticeAnswer" :loading="submitting">
          提交答案
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userFavorite from '@/api/userFavorite'
import userAnswer from '@/api/userAnswer'

export default {
  data() {
    return {
      favoritesList: [],
      total: 0,
      currentPage: 1,
      pageSize: 8,
      practiceDialogVisible: false,
      selectedQuestion: null,
      practiceAnswer: '',
      practiceAnswerArray: [],
      submitting: false,
      loading: false
    }
  },
  computed: {
    userId() {
      return this.$store.getters.userId || 1
    },
    hasPracticeAnswer() {
      if (!this.selectedQuestion) return false

      if (this.selectedQuestion.questionType === 'multiple') {
        return this.practiceAnswerArray.length > 0
      } else {
        return this.practiceAnswer.trim() !== ''
      }
    }
  },
  mounted() {
    this.getFavoritesList()
  },
  methods: {
    // 获取收藏列表
    getFavoritesList() {
      this.loading = true
      userFavorite.getUserFavorites(this.userId).then(res => {
        if (res.code === 200) {
          this.favoritesList = res.data.map(item => ({
            ...item,
            removing: false
          }))
          this.total = this.favoritesList.length
        } else {
          this.$message.error(res.message || '获取收藏列表失败')
        }
      }).catch(() => {
        this.$message.error('获取收藏列表失败')
      }).finally(() => {
        this.loading = false
      })
    },

    // 刷新收藏列表
    refreshFavorites() {
      this.getFavoritesList()
      this.$message.success('刷新成功')
    },

    // 分页 - 每页显示条数变化
    handleSizeChange(size) {
      this.pageSize = size
      this.getFavoritesList()
    },

    // 分页 - 当前页变化
    handleCurrentChange(page) {
      this.currentPage = page
      this.getFavoritesList()
    },

    // 练习题目
    practiceQuestion(question) {
      this.selectedQuestion = question
      this.practiceAnswer = ''
      this.practiceAnswerArray = []
      this.practiceDialogVisible = true
    },

    // 提交练习答案
    submitPracticeAnswer() {
      if (!this.hasPracticeAnswer) {
        this.$message.warning('请先填写答案')
        return
      }

      const answerContent = this.selectedQuestion.questionType === 'multiple'
        ? this.practiceAnswerArray.join(',')
        : this.practiceAnswer

      const answerData = {
        questionId: this.selectedQuestion.questionId,
        answerContent: answerContent,
        userId: this.userId
      }

      this.submitting = true
      userAnswer.submitAnswer(answerData).then(res => {
        if (res.code === 200) {
          this.$message.success('答案提交成功')
          this.practiceDialogVisible = false
        } else {
          this.$message.error(res.message || '提交失败')
        }
      }).catch(() => {
        this.$message.error('提交失败')
      }).finally(() => {
        this.submitting = false
      })
    },

    // 取消收藏
    removeFavorite(favorite) {
      this.$confirm(`确定要取消收藏题目"${favorite.question.title}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        favorite.removing = true
        userFavorite.removeFavorite(this.userId, favorite.questionId).then(res => {
          if (res.code === 200) {
            this.$message.success('取消收藏成功')
            this.getFavoritesList()
          } else {
            this.$message.error(res.message || '取消收藏失败')
          }
        }).catch(() => {
          this.$message.error('取消收藏失败')
        }).finally(() => {
          favorite.removing = false
        })
      })
    },

    // 跳转到练习页面
    goToPractice() {
      this.$router.push('/question/practice')
    },

    // 截断文本
    truncateText(text, length) {
      if (!text) return ''
      if (text.length <= length) return text
      return text.substring(0, length) + '...'
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      return new Date(date).toLocaleString('zh-CN')
    },

    // 获取难度类型样式
    getDifficultyType(level) {
      const typeMap = {
        'easy': 'success',
        'medium': 'warning',
        'hard': 'danger'
      }
      return typeMap[level] || 'info'
    },

    // 获取难度文本
    getDifficultyText(level) {
      const textMap = {
        'easy': '简单',
        'medium': '中等',
        'hard': '困难'
      }
      return textMap[level] || level
    },

    // 获取题目类型文本
    getQuestionTypeText(type) {
      const textMap = {
        'single': '单选题',
        'multiple': '多选题',
        'judge': '判断题',
        'essay': '简答题'
      }
      return textMap[type] || type
    }
  }
}
</script>

<style scoped>
.favorite-item {
  margin-bottom: 20px;
}

.favorite-card {
  height: 300px;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.question-title {
  font-size: 16px;
  font-weight: bold;
  flex: 1;
  margin-right: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.question-content {
  flex: 1;
  overflow: hidden;
  margin-bottom: 15px;
}

.question-content p {
  margin: 0;
  color: #666;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-footer {
  margin-bottom: 10px;
}

.collect-time {
  font-size: 12px;
  color: #999;
  text-align: right;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.practice-question h3 {
  margin-bottom: 20px;
  color: #333;
}

.practice-question .question-content {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.answer-section {
  margin-top: 20px;
}

.options-container {
  margin-bottom: 20px;
}

.option-item {
  display: block;
  margin-bottom: 10px;
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fff;
}

.option-item:hover {
  background-color: #f0f9ff;
  border-color: #409eff;
}
</style>
